import React from 'react'
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import PropTypes from 'prop-types'
import {
  Image, Menu, Icon, Dropdown, Label,
} from 'semantic-ui-react'
import { global as globalDuck, auth0 as auth0Duck } from 'ducks'
import { Subscription } from 'react-apollo'
import GetMessage from 'graphql/headerMenu/pendingMessage.graphql'
import lock from '../auth0'

const options = (signout,link) => [
  {
    key: 'tasks',
    text: '任务中心',
    icon: 'tasks',
    onClick: () => {
      link('/home')
    },
  },
  {
    key: 'sign-out',
    text: '退出登陆',
    icon: 'sign out',
    onClick: () => {
      signout(lock)
    },
  },
]

const DropDownView = ({ user, signOut,link }) => (
  <Dropdown
    trigger={(
      <span>
        <Image avatar src={user.avatar} />
        {user.name}
      </span>
)}
    options={options(signOut,link)}
    icon={null}
  />
)

DropDownView.propTypes = {
  user: PropTypes.object.isRequired,
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  signOut: auth0Duck.creators.actionLogout,
  link: path => push(path),
}

const UserDropDown = connect(
  mapStateToProps,
  mapDispatchToProps,
)(DropDownView)

const MessageCountView = ({ user, link }) => (
  <Menu.Item onClick={() => link('/message')}>
    <Icon name="mail" />
    通知
    <Subscription subscription={GetMessage} variables={{ userTo: user.id }}>
      {({ data, loading, error }) => {
        if (loading) return 'Loading...'
        if (error) return `Error! ${error.message}`
        const { count } = data.message_aggregate.aggregate
        if (count > 0) {
          return (
            <Label color="red" floating>
              {count}
            </Label>
          )
        }
        return null
      }}
    </Subscription>
  </Menu.Item>
)

const MessageCount = connect(
  mapStateToProps,
  mapDispatchToProps,
)(MessageCountView)

export default () => [
  <MessageCount />,
  <Menu.Item>
    <UserDropDown />
  </Menu.Item>,
]
